package com.hg.oa.widget;

import android.app.DownloadManager;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hg.oa.R;

/**
 * Created by fengxiang on 2016/10/9.
 */
public class DownloadDialog {

    String tag = "CalendarViewDialog";

    AlertDialog dialog;
    Button btn_cancel;
    ProgressBar progressBar;
    TextView text_progress;

    public DownloadDialog(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_download, null);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        text_progress = (TextView) view.findViewById(R.id.text_progress);
        btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCancelable(true);
        builder.setView(view);
        builder.setTitle("版本更新");
        builder.setMessage("正在下载...");
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        start(context);
    }

    public void show() {
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }


    void start(Context context) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        String apkUrl = "http://gdown.baidu.com/data/wisegame/0d89baa0cf1f8baa/baidushoujizhushou_16792112.apk";
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
        request.setDestinationInExternalPublicDir("com.hg.oa", "baidushoujizhushou_16792112.apk");
        long downloadId = downloadManager.enqueue(request);
        context.getContentResolver().registerContentObserver(Uri.parse("content://downloads/"), true, new DownloadObserver(context, downloadId));
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            progressBar.setProgress(msg.what);
            text_progress.setText(msg.what + "%");
            if (msg.what == 100) {
                dialog.setMessage("下载完成");
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                    }
                }, 1000);
            }
        }
    };

    public class DownloadObserver extends ContentObserver {
        private long downid;
        private Context context;

        public DownloadObserver(Context context, long downid) {
            super(handler);
            this.downid = downid;
            this.context = context;
        }

        @Override
        public void onChange(boolean selfChange) {
            //每当/data/data/com.android.providers.download/database/database.db变化后，触发onCHANGE，开始具体查询
            super.onChange(selfChange);
            //实例化查询类，这里需要一个刚刚的downid
            DownloadManager.Query query = new DownloadManager.Query().setFilterById(downid);
            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            //这个就是数据库查询啦
            Cursor cursor = downloadManager.query(query);
            while (cursor.moveToNext()) {
                int mDownload_so_far = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                int mDownload_all = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                int mProgress = (mDownload_so_far * 100) / mDownload_all;
                handler.sendEmptyMessage(mProgress);
            }
        }
    }


}
